package com.eling.elcms.travel.service.impl;

import com.eling.elcms.basedoc.model.ContactAddress;
import com.eling.elcms.basedoc.model.PersonalInfo;
import com.eling.elcms.component.excel.Metals;
import com.eling.elcms.core.AppContext;
import com.eling.elcms.core.dao.hibernate.search.SearchCondition;
import com.eling.elcms.core.service.impl.GenericManagerImpl;
import com.eling.elcms.core.util.PropertyUtils;
import com.eling.elcms.core.webapp.util.ExcelUtils;
import com.eling.elcms.member.model.Member;
import com.eling.elcms.member.service.IMemberManager;
import com.eling.elcms.system.model.CommonUser;
import com.eling.elcms.travel.dao.IMailDao;
import com.eling.elcms.travel.model.Mail;
import com.eling.elcms.travel.model.Plan;
import com.eling.elcms.travel.model.Product;
import com.eling.elcms.travel.model.TravelContract;
import com.eling.elcms.travel.model.view.MailRegisterView;
import com.eling.elcms.travel.model.view.MailToExcel;
import com.eling.elcms.travel.model.view.PlanMailView;
import com.eling.elcms.travel.service.IMailManager;
import com.eling.elcms.travel.service.IPlanManager;
import com.eling.elcms.travel.service.IProductManager;
import com.eling.elcms.travel.service.ITravelContractManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
@Service
public class MailManagerImpl extends 
      GenericManagerImpl<Mail, Long> implements IMailManager{
  
	IMailDao mailDao;
	
	@Autowired
	private IMemberManager memberManager;
	@Autowired
	private IProductManager productManager;
	@Autowired
	private IPlanManager planManager;
	@Autowired
	private ITravelContractManager travelContractManager;
	@Autowired
	public void setDao(IMailDao dao) {
        this.dao = dao;
        this.mailDao = dao;
    }
	
		
	@Override
	public List<PlanMailView> queryPlan(String year) {
		
		List<Plan> plans = planManager.queryStatus();
		List<PlanMailView> pmvs = new ArrayList<PlanMailView>();
		
		Member memberCond = new Member();		
		List<Member> member = memberManager.query(memberCond);
				
		Mail mail = new Mail();
		List<Mail> mails = query(mail);
		
		for(int i = 0;i < plans.size();i++){
			    PlanMailView pmv = new PlanMailView();
			    List<Mail> mailConds = new ArrayList<Mail>();
			    SimpleDateFormat df=new SimpleDateFormat("yyyy");
			    //根据年份过滤
			    if(df.format(plans.get(i).getYear()).equals(year)){
				pmv.setPkPlan(plans.get(i).getPkPlan());
				pmv.setYear(plans.get(i).getYear());
				pmv.setVerNumber(plans.get(i).getVerNumber());
				pmv.setPlanTitle(plans.get(i).getPlanTitle());
				pmv.setPublisher(plans.get(i).getPublisher());
				pmv.setPublisherDate(plans.get(i).getPublisherDate());
				pmv.setMemberNum((long) member.size());
				for(int j = 0;j<mails.size();j++){
					if(plans.get(i).getPkPlan().equals(mails.get(j).getPlan().getPkPlan())){
						mailConds.add(mails.get(j));
					}
				}
				pmv.setMailNum((long)mailConds.size());
				pmvs.add(pmv);
				}
		}
		return pmvs;
	}

	
	@Override
	public List<MailRegisterView> queryMail(Mail cond,Long pkPlan,Long addressId) {
		List<MailRegisterView> mailRegisterView = new ArrayList<MailRegisterView>();	
		//查询会员信息	
		TravelContract tc = new TravelContract();
		PropertyUtils.setProperty(tc, "productRule.product.pkProduct", cond.getProduct().getPkProduct());
		List<TravelContract> lists = travelContractManager.query(tc);
		List<Member> members = new ArrayList<Member>();
		for(TravelContract t : lists){
			Set<ContactAddress> contactAddresses = t.getMember().getPersonalInfo().getContactAddresses();
			boolean flag = false;
			for(ContactAddress contactAddress : contactAddresses){
				if(contactAddress.getAddress().getId().equals(addressId)){
					flag = true;
				}
			}
			if(flag){
				members.add(t.getMember());
			}
		}
		Plan plan = planManager.get(pkPlan);
		Product product = productManager.get(cond.getProduct().getPkProduct());
		CommonUser user = (CommonUser) AppContext.curUser();
		List<Mail> mails = new ArrayList<>();
		for(Member member : members){
			Mail mail = new Mail();
			mail.setMember(member);
			mail.setCommonUser(user);
			mail.setMailMethod(cond.getMailMethod());
			mail.setMailTime(new Date());
			mail.setOrganization(user.getOrganization());
			mail.setPlan(plan);
			mail.setProduct(product);
			mail.setVersion(0);
			mails.add(mail);
		}
		save(mails);
		//显示邮寄登记信息
		return mailRegisterView;
	}


	@Override
	public List<Mail> saveMailRegister(Mail cond,Long pkPlan,Long addressId) {
		//查询会员信息	
		TravelContract tc = new TravelContract();
		PropertyUtils.setProperty(tc, "productRule.product.pkProduct", cond.getProduct().getPkProduct());
		List<TravelContract> lists = travelContractManager.query(tc);
		List<Member> members = new ArrayList<Member>();
		for(TravelContract t : lists){
			if(addressId == null){
				members.add(t.getMember());
			}else{
				Set<ContactAddress> contactAddresses = t.getMember().getPersonalInfo().getContactAddresses();
				Long id = 0L;
				if(t.getMember().getPersonalInfo().getAreaAddress()!=null){
					id = t.getMember().getPersonalInfo().getAreaAddress().getId();
				}
				boolean flag = false;
				for(ContactAddress contactAddress : contactAddresses){
					if(null != contactAddress.getAddress()){
						if(contactAddress.getAddress().getId().equals(addressId)){
							flag = true;
						}
					}
				}
				if (id.equals(addressId)) {
					flag = true;
				}
				if(flag){
					members.add(t.getMember());
				}
			}
		}
		Plan plan = planManager.get(pkPlan);
		Product product = productManager.get(cond.getProduct().getPkProduct());
		CommonUser user = (CommonUser) AppContext.curUser();
		List<Mail> mails = new ArrayList<>();
		for(Member member : members){
			Mail mail = new Mail();
			mail.setMember(member);
			mail.setCommonUser(user);
			mail.setMailMethod(cond.getMailMethod());
			mail.setMailTime(new Date());
			mail.setOrganization(user.getOrganization());
			mail.setPlan(plan);
			mail.setProduct(product);
			mail.setVersion(0);
			mails.add(mail);
		}
		return save(mails);
	}


	@Override
	public List<MailRegisterView> queryAll(Mail cond, TravelContract travelContract,Boolean flag) {
		return mailDao.queryAll(cond, travelContract, flag);
	}

	@Override
	public List<MailRegisterView> searchMail(SearchCondition sc,Mail cond) {

		
		List<MailRegisterView> mrvAll = new ArrayList<MailRegisterView>();
		//全部签约会员
		List<TravelContract> list = travelContractManager.search(sc);
		//当前计划下所有发送邮件的会员
		List<Mail> mailList = query(cond);
		//查询全部
		for(TravelContract contract : list){
			boolean flagC = true;//为true 则未邮寄  false 已邮寄
			Mail mailSend = new Mail();
			for(Mail mail : mailList){
				if(contract.getMember().getPkMember().equals(mail.getMember().getPkMember())){
					flagC = false;
					mailSend = mail;
				}
			}
			if(flagC){
				MailRegisterView mailRegisterView = new MailRegisterView();
				mailRegisterView.setMember(contract.getMember());
				mailRegisterView.setStatus("否");
				mrvAll.add(mailRegisterView);
			}else{
				MailRegisterView mailRegisterView = new MailRegisterView();
				mailRegisterView.setMember(mailSend.getMember());
				mailRegisterView.setCommonUser(mailSend.getCommonUser());
				mailRegisterView.setMailMethod(mailSend.getMailMethod());
				mailRegisterView.setMailTime(mailSend.getMailTime());
				mailRegisterView.setPkMail(mailRegisterView.getPkMail());
				mailRegisterView.setStatus("是");
				mrvAll.add(mailRegisterView);
			}
		}
		return mrvAll;
	}

	@Override
	public void toExcel(HttpServletResponse resp, String status, Long pkPlan,
			Long pkProduct) {
		
		String fetchProperties = "pkMail,member.pkMember," +
				"member.personalInfo.name," +
				"member.personalInfo.sex.*,"+
				"member.personalInfo.idNumber,"+
				"member.personalInfo.mobilePhone,"+
				"member.personalInfo.address,"+
				"member.personalInfo.contactAddresses.*,"+
				"member.personalInfo.contactAddresses.address.fullName,"+
				"member.personalInfo.houseRegister,"+
				"member.personalInfo.houseRegister.fullName," +
				"member.personalInfo.address," +
				"member.personalInfo.address.fullName," +
				"member.personalInfo.contactAddresses.communityData.name,"+
				"mailMethod,status,commonUser,commonUser.name,mailTime";
		Mail cond =new Mail();		
		TravelContract travelContract = new TravelContract();
		Boolean flag = null;
		PropertyUtils.setProperty(cond, "fetchProperties", fetchProperties);
		PropertyUtils.setProperty(cond, "plan.pkPlan", pkPlan);
		
		PropertyUtils.setProperty(travelContract, "fetchProperties", fetchProperties);
		PropertyUtils.setProperty(travelContract, "productRule.product.pkProduct", pkProduct);
		if(status.equals("false")){
			flag = false;
		}else if(status.equals("true")){
			flag = true;
		}
		
		List<MailRegisterView> queryAll = mailDao.queryAll(cond, travelContract,flag);
		
		List<MailToExcel> excel = new ArrayList<>();
		
		for(MailRegisterView m : queryAll){
			MailToExcel mt = new MailToExcel();
			String name = null;
			PersonalInfo p = null;
			if(m.getMember().getPersonalInfo()!=null){
				name = m.getMember().getPersonalInfo().getName();
				p = m.getMember().getPersonalInfo();
			}else{
				continue;
			}
			mt.setName(name);
			String display = null;
			if(p.getSex()!=null){
				display = p.getSex().getDisplay();
				mt.setSex(display);
			}
			String mobilePhone = null;
			if(p.getMobilePhone()!=null){
				mobilePhone = p.getMobilePhone();
				mt.setPhone(mobilePhone);
			}
			String address = null;
			if(null!=p.getAddress()){
				address = p.getAddress();
				mt.setAddress(address);
			}
			String display2 = null;
			if(m.getMailMethod()!=null){
				display2 = m.getMailMethod().getDisplay();
				mt.setMailtype(display2);
			}
			if(flag==null){
				if(display2!=null){
					mt.setIsmail("是");
				}else{
					mt.setIsmail("否");
				}
			}else if(flag){
				mt.setIsmail("是");
			}else{
				mt.setIsmail("否");
			}
			String name2 = null;
			if(m.getCommonUser()!=null){
				name2 = m.getCommonUser().getName();
				mt.setOperator(name2);
			}
			String mailTime = null;
			if(m.getMailTime()!=null){
				m.getMailTime().toString();
				mt.setMaildate(mailTime);
			}
			excel.add(mt);
		}
		Properties prop = new Properties();
		prop.setProperty(Metals.DEFAULT_DATE_FORMAT, "yyyy-MM-dd");
		String templateLoacation = "classpath:com/eling/elcms/travel/excel/mail.xlsx";
		Map<String,Object> data = new  HashMap<String,Object>();
		data.put("list", excel);	
		data.put("title", "邮寄基本信息");
		ExcelUtils.mergeForDownload(templateLoacation, data,"邮寄登记.xlsx", prop,resp);
	}

}
